<?php

class IP2Location
{
	/**
	 * validate IP address
	 *
	 * @param string $ip
	 * @return boolean
	 */
	public function __construct()
	{}
	private function checkIpAddr($ip=''){
		return preg_match('/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/i',$ip);
	}
	
	/**
	 * returns IP numer from numerical representation.
	 *       Example: (from Right to Left)
	 *       1.2.3.4 = 4 + (3 * 256) + (2 * 256 * 256) + (1 * 256 * 256 * 256)
	 *       is 4 + 768 + 13,1072 + 16,777,216 = 16,909,060
	 *
	 * @param integer $value
	 * @param boolean $returnAsStr
	 * @return mixed
	 */
	public  function getCountryFromIP($IpsCVS,$ip)
	{
		if($this->checkIpAddr($ip)){
			$iptemp = explode('.', $ip);
			$ipdec = $iptemp[0] * 256 * 256 * 256 + $iptemp[1] * 256 * 256 + $iptemp[2] * 256 + $iptemp[3];
			$file = file_get_contents($IpsCVS);
			if (!strlen($file)) return false;
			$lines = explode("\n", $file);
			foreach($lines as $line){
				$data = trim($line);
				$parts = explode(',', $data);
				if (strlen($line)){
					$parts = explode(',', trim($line));
					if ($ipdec >= $parts[0] && $ipdec <= $parts[1]){
						$country['Code'] = $parts[4];
						$country['Name'] = $parts[6];
						return $country;
					}
				}
			}
		} else
			return false;
	}
	function getIpFromValue($value=0,$returnAsStr=true)
	{
		$ip[0] = floor( intval($value) / (256*256*256) );
		$ip[1] = floor( ( intval($value) - $ip[0]*256*256*256 ) / (256*256) );
		$ip[2] = floor( ( intval($value) -$ip[0]*256*256*256 -$ip[1]*256*256 ) / 256 );
		$ip[3] = intval($value) - $ip[0]*256*256*256 - $ip[1]*256*256 - $ip[2]*256;
		if($returnAsStr){
			return $ip[0].'.'.$ip[1].'.'.$ip[2].'.'.$ip[3];
		}else{
			return $ip;
		}
	}
	
}
?>